package org.xmls.common.base.exception;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.xmls.common.base.exception.enums.GlobalErrCodeEnum;

/**
 * 业务逻辑异常 Exception
 */
@Slf4j
@Data
@EqualsAndHashCode(callSuper = true)
public class ServiceException extends RuntimeException {

    /**
     * 业务错误码
     */
    private Integer code;

    /**
     * 错误提示
     */
    private String message;

    /**
     * 空构造方法，避免反序列化问题
     */
    public ServiceException() {
    }

    public ServiceException(GlobalErrCodeEnum errorCode) {
        this.code = errorCode.getCode();
        this.message = errorCode.getMessage();
    }

    public ServiceException(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public ServiceException setCode(Integer code) {
        this.code = code;
        this.message = GlobalErrCodeEnum.getMessage(code);
        return this;
    }

    public ServiceException(Integer code, String messagePattern, Object... params) {
        this.code = code;
        this.message = doFormat(messagePattern, params);
    }

    public ServiceException(String messagePattern, Object... params) {
        this.code = GlobalErrCodeEnum.COMMON_ERROR.getCode();
        this.message = doFormat(messagePattern, params);
    }

    public ServiceException setMessage(String message) {
        this.message = message;
        return this;
    }

    @Override
    public String getMessage() {
        return message;
    }

    private String doFormat(String messagePattern, Object... params) {
        StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50);
        int i = 0;
        int j;
        int l;
        for (l = 0; l < params.length; l++) {
            j = messagePattern.indexOf("{}", i);
            if (j == -1) {
                if (i == 0) {
                    return messagePattern;
                } else {
                    sbuf.append(messagePattern.substring(i));
                    return sbuf.toString();
                }
            } else {
                sbuf.append(messagePattern, i, j);
                sbuf.append(params[l]);
                i = j + 2;
            }
        }
        if (messagePattern.indexOf("{}", i) != -1) {
        }
        sbuf.append(messagePattern.substring(i));
        return sbuf.toString();
    }
}
